﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Server.ActivityFeed;
using ESF.SharePoint.Utility;
using ESF.SharePoint.Entities;

namespace ESF.SharePoint.ActivityAggregators.Providers
{
    public class LimitChangesUserStatusActivityAggregatorProvider : ActivityAggregatorBaseProvider
    {
        int _defaultMaxItemPerUser = 5;

        public override List<CustomActivityEvent> ProcessActivities(List<CustomActivityEvent> source)
        {
            base.ActivityTypeId = 17;

            Dictionary<string, int> userStatusCount = new Dictionary<string, int>();
            List<CustomActivityEvent> eventsToRemove = new List<CustomActivityEvent>();

            // Max item per user
            int maxItemPerUser;
            int.TryParse(base.Settings["MaxItemPerUser"], out maxItemPerUser);
            if (maxItemPerUser == 0)
                maxItemPerUser = _defaultMaxItemPerUser;

            // Getting only activities of the selected TypeId
            var events = from e in source
                         where e.ActivityTypeId == ActivityTypeId
                         select e;

            DateTime date = DateTime.MinValue;
            foreach (var customEvent in events)
            {
                if (date == DateTime.MinValue)
                    date = customEvent.CreationTime;

                // If current feed is related to new day reset counter
                if (date.DayOfYear != customEvent.CreationTime.DayOfYear)
                {
                    userStatusCount.Clear();
                }
                    
                // Verify if counter of every user change status is to show or hide
                string key = GetKey(customEvent);
                if (userStatusCount.ContainsKey(key))
                {
                    int count = userStatusCount[key];
                    count++;

                    if (count > maxItemPerUser)
                        eventsToRemove.Add(customEvent);
                    else
                        userStatusCount[key] = count;
                }
                else
                    userStatusCount.Add(key, 1);
            }

            // Remove items
            foreach(var eventToRemove in eventsToRemove)
            {
                source.Remove(eventToRemove);
            }

            return source;
        }

        private static string GetKey(CustomActivityEvent customEvent)
        {
            string key;
            Entity publisher = customEvent.Publisher;
            if (publisher != null)
            {
                key = publisher.AccountName;
            }
            else
            {
                ActivityTemplateVariable atv = customEvent.ATV; 
                key = atv.Publisher.AccountName;
            }
            return key;
        }

    }
}
